package com.thinkit.bigdata.core.util.encode;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;

/**
 * 加密算法工具类,MD5和DES
 *
 * @author XINXIN
 */
public class AppCipher {

    //DES加密密钥
    public static final String ENCRYPT_KEY = "key_scrum_monster_des";

    public final static String ALGORITHM_DES = "DES/CBC/PKCS5Padding";

    private final static byte[] IV_DES = {1, 2, 3, 4, 5, 6, 7, 8};

    /**
     * md5加密
     *
     * @param target 待加密字符串
     * @return 加密后的MD5字符串
     */
    @SuppressWarnings("restriction")
    public static String encryptMd5(String target) {
        if (target == null || target.length() <= 0) {
            return null;
        }
        String result = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            result = AppBase64Cipher.encode(md5.digest(target.getBytes(StandardCharsets.UTF_8)));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * DES算法，加密,使用默认key(ENCRYPT_KEY)
     *
     * @param target 待加密字符串
     * @return 加密后的字符串
     */
    public static String encryptDes(String target) {
        return encryptDes(target, ENCRYPT_KEY);
    }

    /**
     * DES算法，加密
     *
     * @param target 待加密字符串
     * @param key 加密私钥，长度不能够小于8位
     * @return 加密后的字符串
     */
    public static String encryptDes(String target, String key) {
        if (target == null || target.length() <= 0) {
            return null;
        }
        try {
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            IvParameterSpec iv = new IvParameterSpec(IV_DES);
            AlgorithmParameterSpec paramSpec = iv;
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
            byte[] bytes = cipher.doFinal(target.getBytes());
            return byte2hex(bytes);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return target;
    }

    /**
     * DES算法，解密,使用默认key(ENCRYPT_KEY)
     *
     * @param target 待解密字符串
     * @return 解密后的字节串
     */
    public static String decryptDes(String target) {
        return decryptDes(target, ENCRYPT_KEY);
    }

    /**
     * DES算法，解密
     *
     * @param target 待解密字符串
     * @param key 解密私钥，长度不能够小于8位
     * @return 解密后的字节串
     */
    public static String decryptDes(String target, String key) {
        if (target == null || target.length() <= 0) {
            return null;
        }
        try {
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            IvParameterSpec iv = new IvParameterSpec(IV_DES);
            AlgorithmParameterSpec paramSpec = iv;
            cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
            return new String(cipher.doFinal(hex2byte(target.getBytes())));
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return target;
    }

    // 二行制转字符串
    private static String byte2hex(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                hs.append('0');
            }
            hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }

    // 二行制转字符数组
    private static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0) {
            throw new IllegalArgumentException();
        }
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        return b2;
    }

    public static void main(String[] args) {
//        for (int i = 0; i < 100; i++) {
//            System.out.println(AppCipher.encryptDes(AppCipher.encryptMd5("admin123"), AppCipher.ENCRYPT_KEY));
//        }

        //System.out.println(encryptDes("1234", ENCRYPT_KEY));
//        System.out.println(decryptDes(encryptDes("1234", ENCRYPT_KEY), ENCRYPT_KEY));

        System.out.println(decryptDes("07D50432FD7C38F2"));

    }

}
